package com.security.control.core.social.wx.connect;

import com.security.control.core.social.wx.api.Wx;
import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.support.OAuth2Connection;
import org.springframework.social.connect.support.OAuth2ConnectionFactory;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2ServiceProvider;

/**
 * @author imoot@gamil.com
 * @date 2019/1/4 0004 11:19
 * -----创建连接工厂
 */
public class WxConnectionFactory extends OAuth2ConnectionFactory<Wx> {

    //使用传入的providerId、appId和appSecret实例化的服务商类、服务商与api（即：自定义相关操作/逻辑类）的适配器来调用父类构造函数创建该服务商的连接工厂
    public WxConnectionFactory(String providerId, String appId, String appSecret) {
        super(providerId, new WxServiceProvider(appId, appSecret), new WxAdapter());
    }

    //微信的openid和accesstoken会一起返回，所以在判断后可以直接获取
    @Override
    protected String extractProviderUserId(AccessGrant accessGrant) {
        if (accessGrant instanceof WxAccessGrant) {
            return ((WxAccessGrant) accessGrant).getOpenId();
        }
        return null;
    }

    @Override
    public Connection<Wx> createConnection(AccessGrant accessGrant) {
        return new OAuth2Connection<Wx>(getProviderId(), extractProviderUserId(accessGrant), accessGrant.getAccessToken(),
                accessGrant.getRefreshToken(), accessGrant.getExpireTime(), getOAuth2ServiceProvider(), getApiAdapter(extractProviderUserId(accessGrant)));
    }

    @Override
    public Connection<Wx> createConnection(ConnectionData data) {
        return new OAuth2Connection<Wx>(data, getOAuth2ServiceProvider(), getApiAdapter(data.getProviderUserId()));
    }

    private ApiAdapter<Wx> getApiAdapter(String providerUserId) {
        return new WxAdapter(providerUserId);//在微信下，不同的人openid不相同，所以要根据不同的openid创建不同的适配器对象交给连接工厂
    }

    private OAuth2ServiceProvider<Wx> getOAuth2ServiceProvider() {
        return (OAuth2ServiceProvider<Wx>) getServiceProvider();
    }
}
